package com.allen.retrofit2_rxjava2.presenter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.allen.retrofit2_rxjava2.network.base.BaseEntry;
import com.allen.retrofit2_rxjava2.network.base.BaseObserver;
import com.allen.retrofit2_rxjava2.network.base.GeneralHttpData;
import com.allen.retrofit2_rxjava2.bean.Banner;
import com.allen.retrofit2_rxjava2.bean.Login;
import com.allen.retrofit2_rxjava2.bean.ZiXunAll;
import com.allen.retrofit2_rxjava2.module.MainContract;
import com.allen.retrofit2_rxjava2.utils.MainUtil;
import com.allen.retrofit2_rxjava2.network.utils.RetrofitUtil;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;


/**
 * @author: Allen.
 * @date: 2018/7/25
 * @description:
 */

public class MainPresenter implements MainContract.presenter {

    private Context context;
    private MainContract.View view;

    public MainPresenter(Context context, MainContract.View view) {
        this.context = context;
        this.view = view;
    }

    /**
     * 图片验证码
     */
    @Override
    public void getCode() {
        RetrofitUtil.getInstance().initRetrofit().getVerityCode().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(ResponseBody value) {
                        InputStream is = value.byteStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(is);
                        view.setCode(bitmap);
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.setContent("失败了----->" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    /**
     * 登录
     *
     * @param user
     * @param pwd
     * @param code
     */
    @Override
    public void userLogin(String user, String pwd, String code) {
        Map<String, String> map = new HashMap<>();
        map.put("userName", user);
        map.put("userPwd", pwd);
        map.put("verifyCode", code);
        RetrofitUtil.getInstance().initRetrofit().userLogin(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Login>(context, MainUtil.loadLogin) {
                    @Override
                    protected void onSuccees(BaseEntry<Login> t) throws Exception {
                        if (t.isSuccess()) {
                            view.setLogin(t.getData());
                        } else {
                            view.setContent("----->" + t.getMessage());
                        }
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        view.setContent("失败了----->" + e.getMessage());
                    }
                });
    }

    /**
     * 获取banner
     */
    @Override
    public void getBannerData() {
        RetrofitUtil.getInstance().initRetrofit().getBanner()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List<Banner>>(context, MainUtil.loadTxt) {
                    @Override
                    protected void onSuccees(BaseEntry<List<Banner>> t) throws Exception {
                        MainUtil.printLogger(t.getData().get(0).getTitle());
                        view.setContent(t.getData().get(0).getContent());
                    }


                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        view.setContent("失败了----->" + e.getMessage());
                    }
                });
    }

    /**
     * 获取资讯
     */
    @Override
    public void getLiveData() {
        RetrofitUtil.getInstance().initRetrofit().getZixunData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<List<ZiXunAll>>(context, MainUtil.loadTxt) {
                    @Override
                    protected void onSuccees(BaseEntry<List<ZiXunAll>> t) throws Exception {
                        view.setContent("标题：" + t.getData().get(0).getTitle());
                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        view.setContent("失败了----->" + e.getMessage());
                    }
                });
    }

    @Override
    public void setTokenTest() {

        RetrofitUtil.getInstance().initRetrofit().setTokenTest("L2ZybXlLQStzKzRCUklXYngrZDdWcXYxNDRWNW16cDVwTXI1dFZpL0dZYnQ3VHQwM2FNa1hvSEpiT1JkOXhRYTRmdWx6NFFhdHArdXBnQTFDbVc4QVE9PQ==")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(ResponseBody value) {
                        InputStream is = value.byteStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(is);
                        view.setCode(bitmap);
                    }

                    @Override
                    public void onError(Throwable e) {
                        view.setContent("失败了----->" + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                    }
                });


    }


    // 映射类
    public void setData(String content, Class<? extends GeneralHttpData> data) {
        try {
            Gson gson = new Gson();
            JsonObject jsonObject = gson.fromJson(content, JsonObject.class);

            GeneralHttpData generalHttpData = data.newInstance();
            generalHttpData = gson.fromJson(jsonObject, generalHttpData.getClass());
//            Logger.verbose("数据" + generalHttpData);
            //setGeneralHttpData(generalHttpData);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    // 映射类
    public void setDataLis(String content, Type type, List<? extends GeneralHttpData> list) {
        try {
            Gson gson = new Gson();
//            List<SignalData> list = new ArrayList<SignalData>();
//            Type type = new TypeToken<List<SignalData>>() {
//            }.getType();
            JsonObject jsonObject = gson.fromJson(content, JsonObject.class);
            list = gson.fromJson(jsonObject.get("data"), type);
            //  setGeneralHttpDatasList(list);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
